<template>
  <div class="dashboard">
    <h2 class="page-title">数据概览</h2>
    
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background: #409eff">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.totalUsers }}</div>
              <div class="stat-label">总用户数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background: #67c23a">
              <el-icon><Goods /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.totalProducts }}</div>
              <div class="stat-label">商品总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background: #e6a23c">
              <el-icon><List /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.totalOrders }}</div>
              <div class="stat-label">订单总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background: #f56c6c">
              <el-icon><Money /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ stats.totalRevenue }}</div>
              <div class="stat-label">总营收</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 最近订单 -->
    <el-card class="recent-orders">
      <template #header>
        <div class="card-header">
          <span>最近订单</span>
          <el-button type="primary" link @click="goToOrders">查看全部</el-button>
        </div>
      </template>
      
      <el-table :data="recentOrders" v-loading="loading">
        <el-table-column prop="id" label="订单ID" width="200" />
        <el-table-column prop="username" label="用户" width="150" />
        <el-table-column label="商品" width="200">
          <template #default="{ row }">
            {{ row.items?.[0]?.name || '-' }}
            <span v-if="row.items?.length > 1">等{{ row.items.length }}件</span>
          </template>
        </el-table-column>
        <el-table-column label="总价" width="120">
          <template #default="{ row }">
            ¥{{ row.total_amount }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180" />
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getOrderList, getOrderStats } from '@/api/order'
import { getUserList } from '@/api/user'
import { getProductList } from '@/api/product'

const router = useRouter()
const loading = ref(false)

const stats = ref({
  totalUsers: 0,
  totalProducts: 0,
  totalOrders: 0,
  totalRevenue: 0
})

const recentOrders = ref([])

// 获取统计数据
const fetchStats = async () => {
  try {
    // 获取用户数
    const usersRes = await getUserList({ page: 1, limit: 1 })
    if (usersRes.code === 200) {
      stats.value.totalUsers = usersRes.data.pagination?.total || 0
    }
    
    // 获取商品数
    const productsRes = await getProductList({ page: 1, limit: 1 })
    if (productsRes.code === 200) {
      // 商品接口返回的是 data.total，不是 data.pagination.total
      stats.value.totalProducts = productsRes.data.total || 0
    }
    
    // 获取订单统计（包含总营收）
    const statsRes = await getOrderStats()
    if (statsRes.code === 200) {
      stats.value.totalOrders = statsRes.data.total || 0
      stats.value.totalRevenue = Number(statsRes.data.totalRevenue || 0).toFixed(2)
    }
    
    // 获取最近订单列表
    const ordersRes = await getOrderList({ page: 1, limit: 10 })
    if (ordersRes.code === 200) {
      recentOrders.value = ordersRes.data.orders || []
    }
  } catch (error) {
    console.error('获取统计数据失败：', error)
  }
}

// 获取订单状态类型
const getStatusType = (status) => {
  const typeMap = {
    pending: 'warning',
    paid: 'success',
    shipped: 'primary',
    completed: 'info',
    cancelled: 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取订单状态文本
const getStatusText = (status) => {
  const textMap = {
    pending: '待支付',
    paid: '已支付',
    shipped: '已发货',
    completed: '已完成',
    cancelled: '已取消'
  }
  return textMap[status] || status
}

// 跳转到订单页面
const goToOrders = () => {
  router.push('/orders')
}

onMounted(async () => {
  loading.value = true
  await fetchStats()
  loading.value = false
})
</script>

<style scoped>
.dashboard {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  font-size: 24px;
  color: #333;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  cursor: pointer;
  transition: transform 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 28px;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.recent-orders {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>

